/**
 * 
 */
package com.blog.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.blog.mapper.SysUserTokenMapper;
import com.blog.pojo.SysUserToken;
import com.blog.service.SysUserTokenService;
import com.blog.util.TokenGenerator;

/**
 * @author zyj
 *
 */
@Service
public class SysUserTokenServiceImpl implements SysUserTokenService {
	
	@Autowired
	private SysUserTokenMapper sysUserTokenMapper;
	
	// 12小时后过期
	private final static int EXPIRE = 3600 * 12;

	@Override
	public SysUserToken findByToken(String token) {
		return sysUserTokenMapper.findByToken(token);
	}

	@Override
	public SysUserToken createToken(Long userId,String token) {
		// 当前时间
		Date now = new Date();
		// 过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
		// 判断是否生成过token
		SysUserToken sysUserToken = findByUserId(userId);
		if(sysUserToken == null){
			sysUserToken = new SysUserToken();
			sysUserToken.setUserId(userId);
			sysUserToken.setToken(token);
			sysUserToken.setLastUpdateTime(now);
			sysUserToken.setExpireTime(expireTime);
			// 保存token，这里选择保存到数据库，也可以放到Redis或Session之类可存储的地方
			sysUserTokenMapper.insertSelective(sysUserToken);
			//save(sysUserToken);
		} else{
			sysUserToken.setToken(token);
			sysUserToken.setLastUpdateTime(now);
			sysUserToken.setExpireTime(expireTime);
			// 如果token已经生成，则更新token的过期时间
			sysUserTokenMapper.updateByPrimaryKeySelective(sysUserToken);
			//save(sysUserToken);
		}
		return sysUserToken;
	}
	
	@Override
	public SysUserToken findByUserId(Long userId) {
		return sysUserTokenMapper.findByUserId(userId);
	}

}
